"""
此脚本用于获取指定xts仓所涉及的部件仓
XTS_SUITE[]:指定需计算的xts仓,支持列表
HOME:全量代码根目录
对应流程:
xts:part_name -> repo_path -> 仓名
"""
import os
import json
import xml.etree.ElementTree as ET

XTS_SUITE = [
    "acts"
]

HOME = os.path.dirname(os.path.abspath(__file__))

MANIFEST_HOME = os.path.join(HOME, ".repo", "manifests")

XTS_HOME = os.path.join(HOME, "test", "xts")

"""
    遍历manifest,获取 路径-repo对应的map
"""

def get_path_repo_map_impl (manifest_home, path_repo_map):
    # print(manifest_home)
    # 遍历XML文件内容
    manifest_xml_list = [manifest_home]
    for xml in manifest_xml_list:
        root = ET.parse(xml).getroot()
        if root.find('include') is not None:
            # print ("in include")
            for child in root.findall('include'):
                get_path_repo_map_impl(os.path.join(MANIFEST_HOME, child.attrib['name']), path_repo_map)
        else:
            # print ("in else")
            for child in ET.parse(xml).getroot().findall('project'):
                if "lite" in child.attrib['path']:
                    continue
                repo_name = child.attrib['name']
                path = child.attrib['path']
                path_repo_map[path] = repo_name

def get_path_repo_map (manifest_home):
    path_repo_map = {}
    get_path_repo_map_impl(manifest_home, path_repo_map)
    return path_repo_map

def run():
    # 遍历manifest,获取 路径-repo对应的map
    # path_repo_map[path] = repo
    path_repo_map = get_path_repo_map(os.path.join(os.path.dirname(MANIFEST_HOME), "manifest.xml"))
    # print(path_repo_map)
    # 根据path_repo_map到对应path查找bundle
    xts_repo = {}
    for xts in XTS_SUITE:
        xts_path = f"//test/xts/{xts}"
        path_set = set()
        dep_txt_path = os.path.join(HOME, f"{xts}_tree.txt")
        with open(dep_txt_path, 'r', encoding='utf-8') as file:
            while True:
                line = file.readline()
                # 文件结束时会返回空字符串，退出循环
                if not line:
                    break
                # 过滤xts仓下的引用
                if xts_path in line:
                    continue
                line = line.strip().split(":")[0]
                path_set.add(line[2:])
        print(path_set)
        print(f"pathset.len = {len(path_set)}")
        repo_set = set()
        # 遍历每一个依赖代码路径
        for path in path_set:
            # 遍历Map中的每一个条目
            for map_path, repo_name in path_repo_map.items():
                # 检查 map_path 是否是 path 的父目录，或者就是 path 本身
                if path.startswith(map_path) and (path == map_path or path[len(map_path)] == '/'):
                    repo_set.add(repo_name)
        xts_repo[xts] = list(repo_set)



    xts_repo_json_file = './xts_repo.json'
    # 将字典写入JSON文件
    with open(xts_repo_json_file, 'w', encoding='utf-8') as json_file:
        json.dump(xts_repo, json_file, ensure_ascii=False, indent=4)


if __name__ == '__main__':
    run()
